#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created by binhou.li on 23/02/2018
# @Copyright

import os
import MySQLdb
import utils
import inotify.adapters
import logging
import config
from dcsInfoExtractor import infoExtractor



class fileNotifier():
    '''
    class of file nofity and db data update
    '''
    def __init__(self, watch_path, db_host, db_user, db_pass, db, recursive_watch=True):
        '''
        :param watch_path: directory to be watched
        :param db_host: mysql host ip
        :param db_user: mysql login user
        :param db_pass: mysql login password
        :param recursive_watch: watch the subdirectories under the watch_path
        '''
        self.watch_path = watch_path
        # self.db_host = db_host
        # self.db_user = db_user
        # self.db_password = db_pass
        # self.database = db
        # #db connect
        # self.db = MySQLdb.connect(self.db_host, self.db_user, self.db_password, self.database)
        # self.cursor = self.db.cursor()

        #
        self.recursive = recursive_watch
        self.fg_list = {}

    def file_notify(self):
        '''
        find new uploaded file and update db info
        :return:
        '''
        i = inotify.adapters.InotifyTree(self.watch_path)
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    logging.debug("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
                             "WATCH-PATH=[%s] FILENAME=[%s]",
                             header.wd, header.mask, header.cookie, header.len, type_names,
                             watch_path.decode('utf-8'), filename.decode('utf-8'))
                    #dir
                    if type_names[0] == 'IN_ISDIR' and type_names[1] == 'IN_CLOSE_NOWRITE':
                        newdir = filename.decode('utf-8')
                        store_path = watch_path.decode('utf-8') + newdir
                        cam_info_id = 1
                        region_oem_id = 1
                        fg_complete = 0
                        status = 0

                        if newdir.endswith('_GMT'):
                            self.fg_list[newdir] = {}
                            sql = 'insert into dcs.webapp_raw_file\
                            (name, store_path, cam_info_id, region_oem_id, fg_complete, status)\
                             values("%s", "%s", %d, %d, %d, %d)' % (newdir, store_path, cam_info_id, region_oem_id, fg_complete, status)
                            utils.exec_dml_sql(sql)
                            logging.info('find new data: %s' % newdir)
                        else:
                            logging.error("dir [%s] is created" % newdir)
                    #file
                    elif len(type_names) == 1 and type_names[0] == 'IN_CLOSE_WRITE':
                        upfile = filename.decode('utf-8')
                        if upfile.endswith(config.rtv_end) or upfile.endswith(config.imu_end) or upfile.endswith(config.gps_end):
                            print upfile
                            parent = upfile[:-4]
                            print 'parent: ' + parent
                            file_type = upfile[-4:]
                            print self.fg_list
                            if parent in self.fg_list.keys():
                                self.fg_list[parent][file_type] = 1
                                if len(self.fg_list[parent].keys()) == 3:
                                    info = infoExtractor(watch_path.decode('utf-8'))
                                    sql = 'insert into dcs.webapp_raw_file(name, store_path, cam_info_id, region_oem_id) \
                                            values("%s", "%s", %d, %d)' %(
                                        parent, watch_path.decode('utf-8'), info[cam_info_id], info[region_oem_id]
                                    )
                                    try:
                                        cursor.execute(sql)
                                        db.commit()
                                    except:
                                        logging.error('update sql failed, file %s', upfile)
                                        raise Exception("update sql failed, filegroup %s", upfile)

                            else:
                                logging.error("file [%s] has and his parent dir bad match", upfile)
                        else:
                            logging.error('file [%s] bad filename')
                    else:
                        pass
                    #if header.mask == 8:
        finally:
            pass







if __name__ == '__main__':
    db_host = '10.69.130.43'
    db_user = 'dba'
    db_pass = 'mysql'
    db = 'dcs'
    watch_path = '/tmp/test'
    fn = fileNotifier(watch_path, db_host, db_user, db_pass, db)
    fn.file_notify()
